package com.wyw.hemerocallis.controller;

import com.alibaba.fastjson.JSON;
import com.wyw.hemerocallis.annotation.IgnoreResponseAdvice;
import com.wyw.hemerocallis.service.IJWTService;
import com.wyw.hemerocallis.vo.JwtToken;
import com.wyw.hemerocallis.vo.UsernameAndPassword;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 对外暴露的授权接口
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@RestController
@RequestMapping("/authority")
@RequiredArgsConstructor
public class RestAuthorityController {
    private final IJWTService ijwtService;

    /**
     * 从授权中心获取 Token (其实就是登录功能), 且返回信息中没有统一响应的包装
     * */
    @IgnoreResponseAdvice//可以在类上
    @PostMapping("/token")
    public JwtToken token(@RequestBody UsernameAndPassword usernameAndPassword)
            throws Exception {

        log.info("获取token，参数:{}",
                JSON.toJSONString(usernameAndPassword));
        return new JwtToken(ijwtService.generateToken(
                usernameAndPassword.getUsername(),
                usernameAndPassword.getPassword()
        ));
    }

    /**
     * 注册用户并返回当前注册用户的 Token, 即通过授权中心创建用户
     * */
    @IgnoreResponseAdvice
    @PostMapping("/register")
    public JwtToken register(@RequestBody UsernameAndPassword usernameAndPassword)
            throws Exception {

                log.info("注册用户且返回token，参数:{}", usernameAndPassword );
                log.info("注册用户且返回token，参数:{}", JSON.toJSONString(
                usernameAndPassword
        ));
        return new JwtToken(ijwtService.registerUserAndGenerateToken(
                usernameAndPassword
        ));
    }
}
